<template>
  <el-card class="w-full pt-[5px] pb0">
    <el-radio-group v-model="searchForm.applyState" @change="handleSearch">
      <el-radio-button :label="`全部(${countMap.total})`" value="" />
      <el-radio-button :label="`未启动(${countMap[0]})`" value="0" />
      <el-radio-button :label="`申请中(${countMap[1]})`" value="1" />
      <el-radio-button :label="`已停止(${countMap[2]})`" value="2" />
    </el-radio-group>
    <el-form :model="searchForm" class="mt-[20px]" label-width="110px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="申请计划名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="申请计划名称 " clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目分类" prop="projectTypeIdList">
            <CustomTreeSelect
              :isFetch="false"
              :dataList="projectTypeList"
              placeholder="项目分类"
              v-model="searchForm.projectTypeIdList"
              valueKey="id"
              labelKey="label"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="到期自动结束" prop="isAutoEnd">
            <CommonSelect
              :isFetch="false"
              v-model="searchForm.isAutoEnd"
              :dataList="booleanList"
              placeholder="到期自动结束"
              valueKey="code"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="是否可转入评审" prop="isReview">
            <CommonSelect
              :isFetch="false"
              v-model="searchForm.isReview"
              :dataList="booleanList"
              placeholder="是否可转入评审"
              valueKey="code"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请状态" prop="applyStateList">
            <CustomTreeSelect
              :isFetch="false"
              :dataList="applyStateList"
              placeholder="申请状态"
              v-model="searchForm.applyStateList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0">
            <CommonDateSelect
              placeholder="申请开始日期"
              v-model:startTime="searchForm.beginDate1"
              v-model:endTime="searchForm.beginDate2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0">
            <CommonDateSelect
              placeholder="申请结束日期"
              v-model:startTime="searchForm.endDate1"
              v-model:endTime="searchForm.endDate2"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="handleHistory"> 历史申请 </el-button>
      <el-button type="primary" @click="handleAdd" v-if="verifyRoleType.iskycgly()">
        <el-icon class="mr-[5px]"><Plus /></el-icon>
        新增
      </el-button>
      <template v-if="verifyRoleType.isKymsOrkycgly()">
        <el-button @click="handleDelSelect">
          <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
          删除
        </el-button>
      </template>
    </div>
    <el-table :data="tableData" class="w-full" stripe v-loading="loading" ref="tableRef">
      <el-table-column type="selection" width="40" v-if="!verifyRoleType.isKyry()" />
      <el-table-column prop="name" label="申请计划名称 ">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.id, row.bookId)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="projectTypeId" label="项目分类" width="160">
        <template #default="{ row }">
          <CommonTreeLabel
            :value="row.projectTypeId"
            :dataList="projectTypeList"
            labelKey="labelLocal"
          />
        </template>
      </el-table-column>
      <el-table-column prop="beginDate" label="申请开始日期" width="120">
        <template #default="{ row }">
          <DateLabel :value="row.beginDate" />
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="申请结束日期" width="120">
        <template #default="{ row }">
          <DateLabel :value="row.endDate" />
        </template>
      </el-table-column>
      <el-table-column prop="appliedNum" label="已申报数" width="80" />
      <el-table-column prop="applyState" label="申请状态" width="80">
        <template #default="{ row }">
          <CommonLabel :dataList="applyStateList" :value="row.applyState" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template #default="{ row }">
          <!-- 科研人员-->
          <template v-if="verifyRoleType.isKyry()">
            <template v-if="row.applyState == '1'">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleSb(row.id, row.projectTypeId)"
                v-if="!row.bookId"
                >申报</el-button
              >
              <el-button
                type="warning"
                size="small"
                plain
                v-if="row.bookId && Number(row.bookCheckStatus) != 2"
                @click="handleRemove(row.bookId)"
                >撤销</el-button
              >
              <el-button type="primary" size="small" plain v-if="row.bookId">打印申报书</el-button>
            </template>
            <el-button
              type="primary"
              size="small"
              plain
              v-if="row.applyState !== '0' && row.bookId"
              @click="handleView(row.bookId)"
              >查看申报</el-button
            >
          </template>
          <!-- 科研秘书或科研管理员 -->
          <template v-if="verifyRoleType.isKymsOrkycgly()">
            <el-button
              type="primary"
              size="small"
              plain
              v-if="row.applyState !== '0'"
              @click="toListPage(row.id, row.projectTypeId)"
              >查看申报</el-button
            >
          </template>
          <!-- 科研管理员 -->
          <template v-if="verifyRoleType.iskycgly()">
            <el-button type="primary" size="small" plain @click="handleEdit(row.id)"
              >编辑</el-button
            >
            <el-button type="primary" size="small" plain @click="handleChange(row)">
              {{ row.applyState == 1 ? "结束" : "启动" }}
            </el-button>
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleToReview(row.id, row.name)"
              v-if="row.applyState == 2 && row.isReview == 1 && row.hasEnteredReview == 0"
              >转入评审</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @save-success="handleSearch" />
  <ViewModal ref="viewModalRef" />
  <AddSbModal ref="sbModalRef" @add-success="handleSearch" v-if="sbModalVisible" />
  <ViewSbModal ref="viewSbModalRef" v-if="viewSbModalVisible" />
  <ToReviewModal ref="toReviewModalRef" @save-success="handleSearch" />
  <HistoryApplyModal ref="historyApplyModalRef" />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import { getList, delRecords, changeState, delSb, getCount } from "@/api/project/xj/sbxm";
import CommonDateSelect from "@/views/project/components/CommonDateSelect.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import DateLabel from "@/views/project/components/DateLabel.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import EditModal from "./components/EditModal.vue";
import ViewModal from "./components/ViewModal.vue";
import HistoryApplyModal from "./components/HistoryApplyModal.vue";
import AddSbModal from "@/views/project/xj/sbxm/sbcl/components/AddModal.vue";
import ViewSbModal from "@/views/project/xj/sbxm/sbcl/components/ViewModal.vue";
import ToReviewModal from "@/views/project/xj/xmps/index/components/EditModal.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { verifyRoleType } from "@/utils/main";
import { formatDate } from "@/utils/formatTime";
import useCommonFetch from "@/hooks/useCommonFetch";
const projectTypeList = useCommonFetch("项目分类（校级）");
const booleanList = useCommonFetch("是或否（存储值：1/0）");
const applyStateList = useCommonFetch("申报状态");
const router = useRouter();
const searchFormOpen = ref(false);
const searchFormRef = ref();
const editModalRef = ref();
const viewModalRef = ref();
const historyApplyModalRef = ref();
const tableRef = ref();
const viewSbModalRef = ref(); //科研人员查看申报材料弹窗
const viewSbModalVisible = ref(false);
const sbModalRef = ref(); //科研人员点击申报弹窗
const sbModalVisible = ref(false);
const toReviewModalRef = ref(); //科研管理员点击转入评审
const countMap = ref({
  total: 0,
  0: 0,
  1: 0,
  2: 0,
});
const searchForm = ref({
  applyState: "",
  name: "",
  projectTypeIdList: [],
  isAutoEnd: "", //到期自动结束
  isReview: "", //是否可转入评审
  applyStateList: [], //申请状态
  beginDate1: "",
  beginDate2: "",
  endDate1: "",
  endDate2: "",
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNum: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击历史申请
const handleHistory = () => {
  historyApplyModalRef.value.view();
};
//点击新增
const handleAdd = () => {
  editModalRef.value.add();
};
//点击编辑
const handleEdit = (id) => {
  editModalRef.value.edit(id);
};
//点击名称查看申报计划
const handleShow = (id, bookId) => {
  viewModalRef.value.view(id, bookId);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  //判断要删除的申报计划中是否有申报材料的
  let flag = false;
  for (let i = 0; i < selectRows.length; i++) {
    if (selectRows[i].appliedNum > 0) {
      flag = true;
      break;
    }
  }
  if (flag) {
    ElMessage({
      message: "选择的申报计划中有申请材料，请先删除申请材料再删除申报计划！",
      type: "error",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  handleDelete(delRecords, ids);
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
    applyState: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      0: 0,
      1: 0,
      2: 0,
    };
    let totalCount = 0;
    res.data.forEach((item) => {
      countMap.value[item.applyState] = item.count;
      totalCount += item.count;
    });
    countMap.value.total = totalCount;
  } catch (error) {
    console.log(error);
  }
}
//启动或停止申报
const handleChange = async (row) => {
  try {
    //启动时判断申报结束时间是否大于当前时间
    if (row.applyState != 1 && new Date().getTime() > new Date(row.endDate).getTime()) {
      ElMessage({
        message: `申报计划已经在${formatDate(
          row.endDate,
          "YYYY-MM-DD"
        )}结束申请，若需重新启动请先修改申请结束日期`,
        type: "error",
      });
      return;
    }
    const params = {
      id: row.id,
      applyState: row.applyState == 1 ? 2 : 1,
      name: row.name,
      endDate: formatDate(row.endDate, "YYYY-MM-DD"),
    };
    const res = await changeState(params);
    if (res.code == 200) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      handleSearch();
    }
  } catch (error) {
    console.log(error);
  }
};
//科研管理员点击查看申报
const toListPage = (id, projectTypeId) => {
  router.push(`/project/xj/sbcl/index?id=${id}&projectTypeId=${projectTypeId}`);
};
//点击转入评审 applyInfoId:评审计划id applyName:评审计划名称
const handleToReview = (applyInfoId, applyName) => {
  toReviewModalRef.value.add(applyInfoId, applyName);
};
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.beginDate1 = "";
  searchForm.value.beginDate2 = "";
  searchForm.value.endDate1 = "";
  searchForm.value.endDate2 = "";
  handleSearch();
};
/** 科研人员相关*/
//点击申报 applyInfoId:申报计划id projectTypeId:项目分类id
const handleSb = (applyInfoId, projectTypeId) => {
  sbModalVisible.value = true;
  nextTick(() => {
    sbModalRef.value.add(applyInfoId, projectTypeId);
  });
};
//科研人员查看申报
const handleView = (bookId) => {
  viewSbModalVisible.value = true;
  nextTick(() => {
    viewSbModalRef.value.view(bookId);
  });
};
//撤销申报
const handleRemove = (id) => {
  ElMessageBox.confirm("项目撤销后，项目信息将自动从系统中删除！", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const params = {
        ids: [id],
      };
      const res = await delSb(params);
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        handleSearch();
      }
    } catch (error) {
      console.log(error);
    }
  });
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
